package com.car.mapper;

import com.car.pojo.Car;
import com.car.pojo.CarQueryParam;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 汽车数据访问接口
 */
@Mapper
public interface CarMapper {

    /**
     * 根据ID查询汽车信息
     */
    @Select("select id, brand, model, plate_number, year, mileage, color, user_id, remark, create_time, update_time from car where id = #{id}")
    Car selectById(Integer id);

    /**
     * 根据用户ID查询车辆列表
     */
    @Select("select c.id, c.brand, c.model, c.plate_number, c.year, c.mileage, c.color, c.user_id, c.remark, c.create_time, c.update_time " +
            "from car c join user u on c.user_id = u.id " +
            "where user_id = #{userId}")
    List<Car> selectByUserId(Integer userId);

    /**
     * 根据用户ID查询车辆数量
     */
    @Select("select COUNT(*) \n" +
            "from car c \n" +
            "join user u on c.user_id = u.id\n" +
            "where c.user_id = #{userId};")
    Integer selectByUserIdCar(Integer userId);

    /**
     * 条件查询汽车信息
     */
    List<Car> list(CarQueryParam param);

    /**
     * 新增汽车
     */
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into car(brand, model, plate_number, year, mileage, color, user_id, remark, create_time, update_time) " +
            "values (#{brand}, #{model}, #{plateNumber}, #{year}, #{mileage}, #{color}, #{userId}, #{remark}, #{createTime}, #{updateTime})"
    )
    void insert(Car car);

    /**
     * 根据ID更新汽车信息
     */

    void updateById(Car car);
    /**
     * 根据ID批量删除汽车
     */
    @Delete("<script>delete from car where id in <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
    void deleteByIds(List<Integer> ids);
    /**
     * 删除单个车辆
     */
    @Delete("delete from car where id = #{id}")
    void delete(Integer id);

    /**
     * 查询所有汽车
     */
    @Select("select id, brand, model, plate_number, year, mileage, color, user_id, remark, create_time, update_time from car")
    List<Car> queryAll();
    
    /**
     * 检查车牌号是否已存在（除了指定ID的车辆）
     */
    @Select("select count(*) from car where plate_number = #{plateNumber} and id != #{id} and user_id = #{userId}")
    int countByPlateNumberExcludeId(String plateNumber, Integer id, Integer userId);
}